/**
 * 
 */
package org.intelligentsia.artifacts;

import java.io.Serializable;
import java.util.StringTokenizer;

/**
 * @author geronimo
 * 
 */
public class ArtifactIdentifier implements Serializable {

	private static final long	serialVersionUID	= 4702119966025396690L;
	private final String		groupId;
	private final String		artifactId;
	private final String		version;

	/**
	 * Build a new instance of <code>ArtifactIdentifier</code>
	 * 
	 * @param groupId
	 * @param artifactId
	 * @param version
	 */
	public ArtifactIdentifier(String groupId, String artifactId, String version) {
		super();
		this.groupId = groupId;
		this.artifactId = artifactId;
		this.version = version;
	}

	public ArtifactIdentifier(ArtifactIdentifier identifier) {
		this.groupId = identifier.groupId;
		this.artifactId = identifier.artifactId;
		this.version = identifier.version;
	}

	public ArtifactIdentifier(String artefact) {
		this(parse(artefact));
	}

	public String getGroupId() {
		return this.groupId;
	}

	public String getArtifactId() {
		return this.artifactId;
	}

	public String getVersion() {
		return this.version;
	}

	public Boolean isSnapshot() {
		return version.endsWith("SNAPSHOT");
	}

	@Override
	public String toString() {
		return this.groupId + ":" + this.artifactId + ":" + this.version;
	}

	public static final ArtifactIdentifier parse(String value) {
		StringTokenizer tokenizer = new StringTokenizer(value, ":");
		String g = tokenizer.nextToken();
		String a = tokenizer.nextToken();
		String v = tokenizer.nextToken();
		return new ArtifactIdentifier(g, a, v);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((this.artifactId == null) ? 0 : this.artifactId.hashCode());
		result = prime * result + ((this.groupId == null) ? 0 : this.groupId.hashCode());
		result = prime * result + ((this.version == null) ? 0 : this.version.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ArtifactIdentifier other = (ArtifactIdentifier) obj;
		if (this.artifactId == null) {
			if (other.artifactId != null)
				return false;
		} else if (!this.artifactId.equals(other.artifactId))
			return false;
		if (this.groupId == null) {
			if (other.groupId != null)
				return false;
		} else if (!this.groupId.equals(other.groupId))
			return false;
		if (this.version == null) {
			if (other.version != null)
				return false;
		} else if (!this.version.equals(other.version))
			return false;
		return true;
	}

}
